package com.qishon.pc.domain.service;

import com.qishon.pc.domain.util.ZipUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by yongwei.chen on 2017/1/9.
 */
@Slf4j
@Service
public class DownloadZipService {
    /**
     *
     * @param fileName 文件名
     * @param response
     * @return
     */

    public  HttpServletResponse downloadZip(String fileName, HttpServletResponse response) {
        File file=null;
        try {
            // 以流的形式下载文件。
            file=new File(fileName);
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");

            //如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            try {
                //File f = new File(file.getPath());
                // f.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    //打包
    public void zip(String zipFileName, File inputFile,String fileName) throws Exception {
        ZipUtils.zip(zipFileName,inputFile,fileName);
    }

}
